﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WanMeiCommon;
using WanMeiModel;
using WanMeiSqlTools;

namespace WanMeiBussinessService
{
    public class RaidService : IRaidService
    {

        #region IRaidService 成员
        /// <summary>
        /// 获取所有副本列表信息
        /// </summary>
        /// <returns></returns>
        public List<RaidItem> GetRaidList()
        {
            var result = new List<RaidItem>();
            string sql = "select * from C_Raid where PublicStatus=1";
            var dt = new SqlManager().ExecuteDataset(CommandType.Text, sql, null);
            if (dt != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    result.Add(new RaidItem()
                    {
                        Id = Convert.ToInt32(dt.Tables[0].Rows[i]["Id"]),
                        RaidName = dt.Tables[0].Rows[i]["RaidName"].ToString(),
                        Introduce = dt.Tables[0].Rows[i]["Introduce"].ToString(),
                        NeedLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["NeedLevel"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, RaidUpload.Instance.FolderName, dt.Tables[0].Rows[i]["RaidScreenImg"].ToString()),
                    });
                }

            }
            return result;
        }

        /// <summary>
        /// 获取副本的怪
        /// </summary>
        /// <param name="radiId"></param>
        /// <returns></returns>
        public List<MonsterModel> GetMonsterList(int radiId)
        {
            var result = new List<MonsterModel>();
            SqlParameter[] parms = 
                 {
                    new SqlParameter("@raidId",radiId)
                    
                 };
            StringBuilder sb = new StringBuilder();
            var dt = new SqlManager().ExecuteDataset(CommandType.StoredProcedure, "wanmei_proc_getmonsters", parms);
            if (dt != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    result.Add(new MonsterModel()
                    {
                        Id = Convert.ToInt32(dt.Tables[0].Rows[i]["Id"]),
                        MonsterName = dt.Tables[0].Rows[i]["MonsterName"].ToString(),
                        HeathValue = Convert.ToInt32(dt.Tables[0].Rows[i]["HeathValue"]),
                        MagicValue = Convert.ToInt32(dt.Tables[0].Rows[i]["MagicValue"]),
                        ExValue = Convert.ToInt32(dt.Tables[0].Rows[i]["ExValue"]),
                        MonsterLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["MonsterLevel"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, MonsterUpload.Instance.FolderName, dt.Tables[0].Rows[i]["ImgPath"].ToString()),
                        PotentialValue = Convert.ToInt32(dt.Tables[0].Rows[i]["PotentialValue"]),
                        IsHasSkill = Convert.ToInt32(dt.Tables[0].Rows[i]["IsHasSkill"]),
                        SkillImg = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, SkillUpload.Instance.FolderName, dt.Tables[0].Rows[i]["SkillImg"].ToString()),
                        SkillCd = Convert.ToInt32(dt.Tables[0].Rows[i]["SkillCd"]),
                        SkillValue = Convert.ToInt32(dt.Tables[0].Rows[i]["SkillValue"]),
                        Ap = Convert.ToInt32(dt.Tables[0].Rows[i]["Ap"]),
                        ApImg = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, SkillUpload.Instance.FolderName, dt.Tables[0].Rows[i]["ApImg"].ToString()),
                        ApInteral = Convert.ToInt32(dt.Tables[0].Rows[i]["ApInteral"]),
                        Money = Convert.ToInt32(dt.Tables[0].Rows[i]["Money"]),
                    });
                }
            }
            return result;
        }

        /// <summary>
        /// 获取战斗处理结果
        /// </summary>
        /// <param name="monsters"></param>
        /// <param name="fightStatus"></param>
        /// <param name="un"></param>
        /// <returns></returns>
        public RaidFightResultModel GetRaidFightHandleResult(GetRaidFightHandleResultParams parms)
        {
            var result = new RaidFightResultModel();
            var sqlManager = new SqlManager();
            SqlParameter rtn_err = sqlManager.GetRtnParameter();
            SqlParameter[] sqlparms = 
            {
                new SqlParameter("@un",SecretClass.DecryptQueryString(parms.Un)),
                new SqlParameter("@heroId",parms.HeroId),
                new SqlParameter("@fightStatus",parms.FightStatus),
                new SqlParameter("@potentialValues",parms.PotentialValues),
                new SqlParameter("@money",parms.Money),
                new SqlParameter("@raidId",parms.RaidId),
                new SqlParameter("@roleCurrentExValues",parms.RoleCurrentExValues),
                new SqlParameter("@roleCurrentLevel",parms.RoleCurrentLevel),
                new SqlParameter("@roleCurrentHealth",parms.RoleCurrentHealth),
                new SqlParameter("@roleCurrentMagic",parms.RoleCurrentMagic),
                new SqlParameter("@roleCurrentArmor",parms.RoleCurrentArmor),
                new SqlParameter("@roleCurrentCritical",parms.RoleCurrentCritical),
                new SqlParameter("@roleCurrentAp",parms.RoleCurrentAp),
                rtn_err
            };
            var ds = sqlManager.ExecuteDataset(CommandType.StoredProcedure, "wanmei_pro_getraidhandleresult", sqlparms);
            if (rtn_err.Value.ToString() != "1")
            {
                result.ProcResult = Convert.ToInt32(rtn_err.Value);
                return result;
            }
            if (parms.FightStatus == 1 && ds != null && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    result.Props.Add(new RaidFightPropItem()
                    {
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, PropUpload.Instance.FolderName, ds.Tables[0].Rows[i]["ImgPath"].ToString()),
                        PropName = ds.Tables[0].Rows[i]["PropName"].ToString(),
                        DropRate = Convert.ToInt32(ds.Tables[0].Rows[i]["DropRate"]),
                        ProType = Convert.ToInt32(ds.Tables[0].Rows[i]["ProType"]),
                        Place = Convert.ToInt32(ds.Tables[0].Rows[i]["Place"]),
                        ProId = Convert.ToInt32(ds.Tables[0].Rows[i]["ProId"]),
                        RoleId = Convert.ToInt32(ds.Tables[0].Rows[i]["RoleId"]),
                        SalePrice = Convert.ToInt32(ds.Tables[0].Rows[i]["SalePrice"]),
                        IsHas = Convert.ToInt32(ds.Tables[0].Rows[i]["IsHas"])
                    });
                }
                result.Props = DoPropList(result.Props);
                //入库
                InsertRoleBackPack(result.Props, parms.HeroId, parms.Un);
            }

            result.ProcResult = 1;
            return result;
        }
        /// <summary>
        /// 副本掉落的物品进行入库，如果非装备的道具，如果背包里有该物品，更新数量。
        /// </summary>
        /// <param name="list"></param>
        /// <param name="heroId"></param>
        /// <param name="un"></param>
        private void InsertRoleBackPack(List<RaidFightPropItem> list, int heroId, string un)
        {
            var sqlManager = new SqlManager();
            var sqlList = new List<string>();
            list.ForEach(prop =>
            {
                if (prop.IsHas > 0 && prop.ProType != 1)
                {
                    //当前角色背包存在该道具，叠加数量
                    sqlList.Add(string.Format("update C_BackPack set Num = Num+{0} where PropId= {1} and PropType={2}and HeroId={3} and UserName='{4}'", prop.Num, prop.ProId, prop.ProType, heroId, SecretClass.DecryptQueryString(un)));
                }
                else
                {
                    sqlList.Add(string.Format("insert into C_BackPack(RoleId,PropType,PropId,Num,GetMsg,UserName,HeroId,SalePrice,IsUseing,EquipmentLevel,Place)values({0},{1},{2},{3},'{4}','{5}',{6},{7},0,0,{8})", prop.RoleId, prop.ProType, prop.ProId, prop.Num, "副本", SecretClass.DecryptQueryString(un), heroId, prop.SalePrice, prop.Place));
                }
            });
            sqlManager.ExecTransactionAsUpdate(sqlList.ToArray(), null);
        }
        /// <summary>
        /// 存储过程返回当前副本胜利的随机3个道具，这里进行处理。循环=》概率过滤=》根据道具类型生成数量
        /// proptype1装备，2材料，3宝石,限定数量装备：1.材料：最多5.宝石：最多3
        /// </summary>
        /// <param name="propList"></param>
        /// <returns></returns>
        private List<RaidFightPropItem> DoPropList(List<RaidFightPropItem> propList)
        {
            var result = new List<RaidFightPropItem>();
            int ranodm = 0;
            propList.ForEach(prop =>
            {
                ranodm = new Random().Next(1, 100);
                if (prop.DropRate >= ranodm)
                {
                    //说明当前道具出了，在概率内
                    switch (prop.ProType)
                    {
                        case 1:
                            prop.Num = 1;
                            break;
                        case 2:
                            prop.Num = new Random().Next(1, 5);
                            break;
                        case 3:
                            prop.Num = new Random().Next(1, 3);
                            break;
                    }
                    result.Add(prop);
                }
            });
            return result;
        }

        #endregion

        #region IWanMeiService 成员

        public void Dispose()
        {

        }

        #endregion
    }
}
